package net.easymvc.core;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CodeImgServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		request.setCharacterEncoding("UTF-8");
		
		final int width = 100, height = 40;
		Random rd = new Random();
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics pen = bi.getGraphics();
		pen.setColor(Color.WHITE);
		pen.fillRect(0, 0, width, height);
		for (int i = 0; i < 5; i++) {
			pen.setColor(Color.BLACK);
			pen.drawLine(rd.nextInt(width/2), rd.nextInt(height/2), rd.nextInt(width), rd.nextInt(height));
		}
		
		char[] codeList = "ABCDEFGHIJLMNOPQRSTUVWXYZabcdefghijlmnopqestuvwxyz1234567890".toCharArray();
		StringBuffer sb = new StringBuffer();
		int len = codeList.length, index;
		for (int i = 0; i < 4; i++) {
			index = rd.nextInt(len);
			pen.setFont(new Font(Font.SANS_SERIF,Font.BOLD,22));
			pen.setColor(new Color(rd.nextInt(255),rd.nextInt(255),rd.nextInt(255)));
			pen.drawString(codeList[index]+"", (i*15)+rd.nextInt(5)+10, 25+rd.nextInt(5));
			sb.append(codeList[index]);
		}
		
		request.getSession().setAttribute("code", sb.toString());
		ImageIO.write(bi, "JPG", response.getOutputStream());
		

	}

}
